package services

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"vala/configs"
	"vala/tools"
)

type NginxService struct {
	Dir          string
	ExecFile     string
	Process      *os.Process
	ProcessState chan *os.ProcessState
}

func NewNginxService(execFile string) *NginxService {
	return &NginxService{
		Dir:          filepath.Dir(execFile),
		ExecFile:     execFile,
		ProcessState: make(chan *os.ProcessState),
	}
}

func (nginxService *NginxService) Start() {
	if !nginxService.Status() {
		nginxService.Process, nginxService.ProcessState = tools.StartProcess(nginxService.ExecFile, []string{})
	}
}

func (nginxService *NginxService) Stop() {
	if nginxService.Status() {
		tools.StartProcess(nginxService.ExecFile, []string{"-s", "quit"})
		// 检查文件
		var pidFile = filepath.Join(nginxService.Dir, configs.NGINX_PID_DIR, configs.NGINX_PID_FILE)
		pidByt, error := ioutil.ReadFile(pidFile)
		if error != nil {
			panic(error)
		}
		// 获取PID
		pid, error := strconv.Atoi(strings.TrimRight(strings.TrimRight(string(pidByt), "\n"),"\r"))
		if error != nil {
			panic(error)
		}
		_, error = os.FindProcess(pid)
		if error != nil {
			os.Remove(pidFile)
		}
	}
}

func (nginxService *NginxService) Reload() {
	tools.StartProcess(nginxService.ExecFile, []string{"-s", "reload"})
}

// 目前仍然以Pid文件是否存在来判断
func (nginxService *NginxService) Status() bool {
	var pidFile = filepath.Join(nginxService.Dir, configs.NGINX_PID_DIR, configs.NGINX_PID_FILE)
	if tools.IsExist(pidFile) {
		pidByt, error := ioutil.ReadFile(pidFile)
		if error != nil {
			return false
		}
		// 获取PID
		pid, error := strconv.Atoi(strings.TrimRight(strings.TrimRight(string(pidByt), "\n"),"\r"))
		if error != nil {
			panic(error)
		}
		_, error = os.FindProcess(pid)
		if error != nil {
			return false
		}

		return true
	}

	return false
}
